import React, {useContext, useEffect} from 'react';
import {View, Alert, ScrollView} from 'react-native';
import {useMount, useDebounceEffect, useMap, useSafeState} from 'ahooks';
import dayjs from 'dayjs';
import {useRoute} from '@react-navigation/native';
import {useSelector, useDispatch} from 'react-redux';
import {Text, Button, Input, Dialog} from '@rneui/themed';
import RNDI from 'react-native-device-info';
import GlobalContext from '@/GlobalContext';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
import globalStyle from '@/style/global.less';
import style from './style.less';

import {CameraRoll, useCameraRoll} from '@react-native-camera-roll/camera-roll';
import callbackToPromise from '@/LocalMongoDbInit/callbackToPromise';
export default ({children}) => {
  const {localMongoDbFileSystem} = useContext(GlobalContext);

  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  const deviceInfo = useSelector(state => state.deviceInfo.value);
  const {uniqueId} = deviceInfo || {};

  const [submitLoading, setSubmitLoading] = useSafeState(false);

  const netdiskMapArr = accountInfo?.j_ext_info?.netdisk_map_arr;
  const [netdiskMap, {set, get, setAll}] = useMap(netdiskMapArr);

  const loopGetSystemFiles = async ({pageSize = 10, after = ''}) => {
    console.log('有新文件要入库', dayjs().format());
    const params = {
      first: pageSize,
      assetType: 'All',
      limited: false,
    };
    if (after) {
      params.after = after;
    }
    const {edges = [], page_info = {}} = await CameraRoll.getPhotos(params);
    const {has_next_page, end_cursor} = page_info;
    const docs = [];
    edges.forEach(item => {
      const {image = {}, type, timestamp} = item?.node || {};
      const {extension, fileSize, uri} = image;
      const doc = {
        extension,
        fileSize,
        type,
        create_dt: timestamp,
        path: uri,
      };
      docs.push(doc);
    });
    for (const doc of new Set(docs)) {
      try {
        const db = localMongoDbFileSystem;
        await db.insertAsync(doc);
      } catch (e) {}
    }

    if (has_next_page) {
      loopGetSystemFiles({pageSize, after: end_cursor});
    }
  };
  //"create_dt_str": "2023-09-07T16:09:24+08:00"
  const ckHasNewFile = async () => {
    const db = localMongoDbFileSystem;
    const m = db.find({}).sort({create_dt: -1}).skip(0).limit(1).exec();
    const docs = await m;
    docs.forEach(item => {
      item.create_dt_str = dayjs(item.create_dt * 1000).format();
    });
    const newDoc = docs[0];
    if (!newDoc) {
      loopGetSystemFiles({});
    } else {
    }

    console.log('newDoc', newDoc);
  };

  useMount(() => {
    ckHasNewFile();
    // (async () => {
    //   const db = localMongoDbFileSystem;
    //   const m = db.find({}).sort({create_dt: -1}).skip(1).limit(2).exec();
    //   const docs = await m;
    //   docs.forEach(item => {
    //     item.create_dt_str = dayjs(item.create_dt * 1000).format();
    //   });
    //   console.log('docsLength', docs);
    // })();
  });

  return (
    <>
      <View style={style.box}>
        <View style={style.header}>
          <View style={style.searchBox}>
            <Input
              placeholder="Search"
              onChangeText={v => {
                console.log('v', v);
              }}
              maxLength={100}
              errorStyle={{
                display: 'none',
              }}
              inputContainerStyle={{
                borderBottomWidth: 0,
                backgroundColor: '#ffffff',
              }}
            />
          </View>
        </View>
        <ScrollView
          style={[
            globalStyle.boxViewBasic,
            {
              flex: 1,
            },
          ]}>
          <Button
            title="Clear all V1.0.0"
            onPress={async () => {
              const db = localMongoDbFileSystem;
              let res = await db.removeAsync({}, {multi: true});
              console.log(res);
            }}
            containerStyle={{
              marginTop: 50,
              marginLeft: 20,
              marginRight: 20,
            }}
          />
        </ScrollView>
      </View>
    </>
  );
};
